package cn.fzc.yipai.thread;

import cn.fzc.yipai.entity.Account;
import cn.fzc.yipai.entity.NewGoodsInfo;
import cn.fzc.yipai.entity.StoreInfo;
import cn.fzc.yipai.utils.HttpUtils;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: fu.zc
 * @Date: 2021/7/15 14:51
 * @Description:
 */
@Slf4j
public class KillGoodsThread implements Runnable {


    /**
     * 下单接口
     */
    public static final String KILL_URL = "https://www.yihui-xh.xyz/yip/otc/order/addorderNew";


    private final HttpUtils httpUtils;

    private final NewGoodsInfo goodsInfo;

    private final StoreInfo storeInfo;

    private final Account accountInfo;


    public KillGoodsThread(HttpUtils httpUtils, NewGoodsInfo goodsInfo, StoreInfo storeInfo, Account accountInfo) {
        this.httpUtils = httpUtils;
        this.goodsInfo = goodsInfo;
        this.storeInfo = storeInfo;
        this.accountInfo = accountInfo;
    }

    @SneakyThrows
    @Override
    public void run() {
        Map<String, Object> reqParam = new HashMap<>();
        reqParam.put("goodsseller_id", goodsInfo.getGoodsSellerVO().getId());
        reqParam.put("goods_id", goodsInfo.getGoodsSellerVO().getGoodsId());
        reqParam.put("stores_id", goodsInfo.getGoodsInfoVO().getStoresId());
        reqParam.put("expireTime", getExpireTime());
        try {
            //发送请求
            String result = httpUtils.executePost(KILL_URL, accountInfo.getToken(), reqParam);

            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getInteger("status") == 1) {
                    log.error("[{}] 成功 ===> req:{}", accountInfo.getAccount(), JSON.toJSONString(reqParam));
                } else {
                    log.warn("[{}] 失败 ==> req:{}, resp: {}", accountInfo.getAccount(), JSON.toJSONString(reqParam), result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int getExpireTime() {
        String endTime = storeInfo.getEndTime();
        return (getNumber(endTime) - getNumber(DateUtil.formatTime(new Date()))) * 1000;
    }


    private static int getNumber(String time) {
        if (time != null) {
            String[] split = time.split(":");
            String e = split[0];
            String i = split[1];
            String o = split[2];

            return Integer.parseInt(e) * 60 * 60 + Integer.parseInt(i) * 60 + Integer.parseInt(o);
        }
        return 0;
    }
}
